<template>
  <a-modal
    v-model:visible="visible"
    :title="title"
    :mask-closable="false"
    :esc-to-close="false"
    width="700px"
    @before-ok="save"
    @close="reset"
  >
    <GiForm ref="formRef" v-model="form" :options="options" :columns="columns" />
  </a-modal>
</template>

<script setup lang="ts">
import { Message } from '@arco-design/web-vue'
import { addMeet, getMeet, updateMeet } from '@/apis/meet/meet'
import { type Columns, GiForm, type Options } from '@/components/GiForm'
import { useForm } from '@/hooks'

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const dataId = ref('')
const isUpdate = computed(() => !!dataId.value)
const title = computed(() => (isUpdate.value ? '修改会议' : '新增会议'))
const formRef = ref<InstanceType<typeof GiForm>>()

const options: Options = {
  form: {
    rules: {
      meetType: [{ required: true, message: '会议类型不能为空!' }],
      name: [{ required: true, message: '会议室不能为空!' }],
      subject: [{ required: true, message: '会议主题不能为空!' }],
      passwordGeneral: [{ required: true, message: '来宾会议密码不能为空!' }],
      passwordChair: [{ required: true, message: '主持人会议密码不能为空!' }]
    }
  },
  btns: { hide: true }
}

const { form, resetForm } = useForm({
  // todo 待补充

})

const columns = computed<Columns<typeof form>>(() => [
  {
    label: '会议类型',
    field: 'meetType',
    type: 'select',
    options: [
      {
        value: 0,
        label: '线下'
      },
      {
        value: 1,
        label: '线上'
      }
    ],
    hide: false,
    span: 24
  },
  {
    label: '会议室',
    field: 'name',
    type: 'select',
    options: [
      {
        value: 'lucy',
        label: 'Lucy'
      }
    ],
    hide: false,
    span: 24
  },
  {
    label: '会议主题',
    field: 'subject',
    type: 'input',
    hide: false,
    span: 24
  },
  {
    label: '来宾会议密码',
    field: 'passwordGeneral',
    type: 'input',
    hide: false,
    span: 24
  },
  {
    label: '主持人会议密码',
    field: 'passwordChair',
    type: 'input',
    hide: false,
    span: 24
  }
])

// 重置
const reset = () => {
  formRef.value?.formRef?.resetFields()
  resetForm()
}

const visible = ref(false)
// 新增
const onAdd = () => {
  reset()
  dataId.value = ''
  visible.value = true
}

// 修改
const onUpdate = async (id: string) => {
  reset()
  dataId.value = id
  console.log('onUpdateonUpdateonUpdateonUpdate')
  const res = await getMeet(id)
  Object.assign(form, res.data)
  visible.value = true
}

// 保存
const save = async () => {
  try {
    const isInvalid = await formRef.value?.formRef?.validate()
    if (isInvalid) return false
    if (isUpdate.value) {
      await updateMeet(form, dataId.value)
      Message.success('修改成功')
    } else {
      await addMeet(form)
      Message.success('新增成功')
    }
    emit('save-success')
    return true
  } catch (error) {
    return false
  }
}

defineExpose({ onAdd, onUpdate })
</script>
